import router from '@/router'
import { asyncRoutes } from '@/router/index.js'
import store from '@/store'
const whiteList = ['/login', '/404']
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式
router.beforeEach(async(to, from, next) => {
  console.log('全局路由导航守卫检查到路由变化', from.path, to.path)
  NProgress.start()

  const token = store.getters.token
  //  首先判断有无token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const roles = await store.dispatch('user/getUserInfo')
        console.log('获取的权限信息是', roles)
        // store.commit()
        // 有了用户数据之后再完成正式的页面跳转

        const filterRoutes = asyncRoutes.filter(route => {
          return roles.menus.includes(route.children[0].name)
        })
        store.commit('menu/setMenuList', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        setTimeout(() => {
          console.log('再完成页面跳转权限上', router.options.routes)
        }, 200)
        next({ ...to, replace: true })
        return
      }
      next()
    }
  } else {
  // 如果没有token
    if (whiteList.indexOf(to.path) > -1) {
    // 如果找到了 表示在在名单里面
      next()
    } else {
      next('/login') // 跳到登录页
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})
